// import axios from 'axios'
import { Message } from 'element-ui'
// import { getToken } from '@/utils/auth'

// // create an axios instance
// const service = axios.create({
//   baseURL: 'http://ihrm-java.itheima.net',
//   // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
//   // withCredentials: true, // send cookies when cross-domain requests
//   timeout: 5000 // request timeout
// })

// // request interceptor
// service.interceptors.request.use(
//   config => {
//     // do something before request is sent
//     if (store.getters.token) {
//       // let each request carry token
//       // ['X-Token'] is a custom headers key
//       // please modify it according to the actual situation
//       config.headers['X-Token'] = getToken()
//     }
//     return config
//   },
//   error => {
//     // do something with request error
//     console.log(error) // for debug
//     return Promise.reject(error)
//   }
// )

// 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
import axios from 'axios'
import store from '@/store'
import router from '@/router'
const service = axios.create({
  // baseURL: '地址B',
  // baseURL: 'http://ihrm-java.itheima.net',
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// 响应拦截器
// 1. 判断本次操作成功失败： response.data.success
// 2. 数据脱壳

// service.interceptors.response.use(函数1， 函数2)
// axios请求状态码小于400  ====> 函数1
// axios请求状态码>=400 || 网络错误  ====> 函数2
service.interceptors.response.use(
  response => {
    if (response.data.success === false) {
      return Promise.reject(new Error(response.data.message))
    } else {
      return response.data
    }
    // const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  async error => {
    console.dir(error)
    if (error.response.status === 401) {
      // 清空信息，类似于用户退出
      await store.dispatch('user/logout')
      router.push('/login?redirect=' + router.currentRoute.fullPath)
    }
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 请求拦截器
service.interceptors.request.use(config => {
  // 如果有token，就带上
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, err => {
  return Promise.reject(err)
})

export default service // 导出axios实例
